from flask import Blueprint, request, json, jsonify
from flask_restful import Resource, Api, reqparse, marshal_with, marshal
from second_flask.methods import db1
from common.utils.get_data import get_data, _get_data
import time
import datetime

statistics_bp = Blueprint('statistics_bp', __name__)

api = Api(statistics_bp)


class OrderStatistics(Resource):
    def get(self):
        sql = "select date,sum(total) as smoney from orders where status=2  group by date"
        res = db1.find_all(sql)
        print('res>>>>', res)
        return 'ok'


class AddCompany(Resource):
    def post(self):
        c_name = get_data()['name']
        print('c_name', c_name)
        url = get_data()['url']
        print('url', url)
        money = get_data()['money']
        print('money', money)
        date = int(time.time())
        print('date', date)
        sql = "insert into market(company,url,money,date) values('%s','%s','%s',%d)" % (c_name, url, money, int(date))
        db1.update(sql)
        db1.commit()
        return jsonify({'code': 200})


class GetCompany(Resource):
    def get(self):
        sql = "select * from market"
        company_list = db1.find_all(sql)
        return jsonify({'code': 200, 'company_list': company_list})


class GetUrl(Resource):
    def get(self):
        id = _get_data()['id']
        sql = "select url from market where id=%d" % (int(id))
        url = db1.find(sql)
        return jsonify({'code': 200, 'url': url})


from flask_mail import Mail, Message
from flask import current_app as app


def send_emails(title, content, emaillist):
    mail = Mail(app)
    m = Message(title, sender='zhy2608347593@163.com', recipients=emaillist)
    m.html = content
    mail.send(m)
    return jsonify({'message': 'ok'})


class AddRecord(Resource):
    def get(self):
        url = _get_data()['url']
        print('url', url)
        email = 'zhy2608347593@163.com'
        send_emails('公司名', url, [email])
        date = int(time.time())
        ip = request.remote_addr
        print('ip>>>>>>', ip)
        sql = "select ip from record where ip='%s'" % (ip)
        res = db1.find(sql)
        if not res:
            sql = "insert into record(url,date,ip) values('%s',%d,'%s')" % (url, int(date), ip)
            db1.update(sql)
            db1.commit()
        else:
            return jsonify({'code': 403, 'message': '已有该ip'})
        return jsonify({'code': 200})


class GetRecord(Resource):
    def get(self):
        end = int(time.time())
        start = datetime.datetime.now() - datetime.timedelta(days=30)
        sql = "select url from market"
        url_list = db1.find_all(sql)
        list = []
        list1 = []
        list3 = []
        for i in url_list:
            # print(i)
            sql = "select sum(money) as money,record.url from market inner join record on market.url=record.url where '%s'<FROM_UNIXTIME(record.date)<'%s' and record.url='%s' group by record.url" % (
                start, end, i['url'])
            record_list = db1.find_all(sql)
            list.append(record_list)
            for n in list:
                list1.append(n[0])
                dict1 = {'name': list1[0]['url'], 'value': list1[0]['money']}
                list3.append(dict1)
        return jsonify({'code': 200, 'record_list': list3})


api.add_resource(OrderStatistics, '/order_statistics', endpoint='order_statistics')
api.add_resource(AddCompany, '/add_company', endpoint='add_company')
api.add_resource(GetCompany, '/get_company', endpoint='get_company')
api.add_resource(GetUrl, '/get_url', endpoint='get_url')
api.add_resource(AddRecord, '/add_record', endpoint='add_record')
api.add_resource(GetRecord, '/get_record', endpoint='get_record')
